<?php
class AppModel extends Model {
/**
 * Load validation messages and form construction.
 */
  public function __construct($id = false, $table = null, $ds = null) {
    if (isset($this->fields)) {
      // load label
      $this->label = Configure::read('infojabotabek.label');
      
      // load help_text
      $this->help_text = Configure::read('infojabotabek.help_text');

      // load messages
      $this->msg = Configure::read('infojabotabek.messages.validation');

      foreach ($this->fields as $f => $r) {

        // Suffix string after label of input field, if
        // rule is specified then asterix (mean required)
        // will be added
        $label_suffix = '';

        // set validation rule
        if ( isset($r['rule']) && !empty($r['rule']) ) {
          $this->validate[$f] = array(
            'rule' => $r['rule'],
            'message' => $this->msg[$r['rule']],
            'required' => true,
          );

          if ($r['rule'] == 'required') {
            $this->validate[$f]['rule'] = 'notEmpty';
          }

          $label_suffix = '<span class="required">*</span>';
        }

        // set label
        if ( isset($this->label[$f]) ) {
          $this->fields[$f]['label'] = $this->label[$f] . $label_suffix;
        }
        // data provider if specified (such as select)
        if ( isset($r['provider']) ) {
          $this->fields[$f]['data'] = $this->{$r['provider']}();
        }
        // set helptext
        if ( isset($this->help_text[$f]) ) {
          $this->fields[$f]['help_text'] = $this->help_text[$f];
        }
        // we set the div if there's no rule set explicitly
        if ( !isset($r['div']) ) {
          $this->fields[$f]['div'] = 'input-' . $f;
        }
      }
    }

    parent::__construct($id, $table, $ds);
  }

/**
 * Check if a given value unique in records.
 * @param array $data Value of the field in form of array.
 * @param string $name Field name which values is going to be checked
 *    its uniqueness.
 * @return bool False if the value already exist.
 */
  public function unique($data, $name){
    $this->reqursive = -1;
    $found = $this->find($this->name.".$name='".$data[$name]."'");
    $same = isset($this->id) && $found[$this->name]['id'] == $this->id;

    return !$found || $found && $same;
  }

/**
 * Check if a given city exists in available cities.
 * @param array $field Field name with its value.
 * @return bool Return true if city exists in available cities.
 */
  public function vCity($field) {
    return in_array($field['city'], Configure::read('infojabotabek.cities'));
  }
}
